<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_api
{
	public $m_CI = NULL;
	
	public $m_arrLib    = array();
	
	public $m_arrUser   = array();
	
	public $douban = null;
	
	public $tsina  = null;
	
	public $taobao = null;
	
	public $tqq    = null;
	
	public $qq      = null;
	
	
	public $douban_uid = null;
	
	public $tsina_uid  = null;
	
	public $taobao_uid = null;
	
	public $tqq_uid    = null;
	
	public $qq_uid     = null;
	
	
	
	public static $toUrl = array(
			T_SINA_TYPE  => 'tsina',
			T_QQ_TYPE    => 'tqq',
			QQ_TYPE      => 'qq',
			DOUBAN_TYPE  => 'douban',
			TAOBAO_TYPE  => 'taobao',
			);
	
	
	
	public function __construct($para = array())
	{
		$this->m_arrLib = $para;
		
		$this->m_CI = &get_instance();
		
		// 载入model
		$this->m_CI->load->model('account/account_m');
		
		// 载入session
		$this->m_CI->load->library('session');
		
		$this->m_arrUser = $this->m_CI->my_member->getUser();
		
		if (empty($this->m_arrUser))
		{
			// 用户竟然没有登陆，怎么进来的 ...
			// TODO: 需要添加一个回调页面
			redirect('account/login');
			exit;
		}
		
		$this->loadPlatform();
		
		$this->getToken();

	}

	
	public function api()
	{
		
	}
	
	private function loadPlatform()
	{
		if (in_array(DOUBAN_TYPE, $this->m_arrLib))
		{
			$this->m_CI->load->config('oauth2');
		
			// 生成一个豆瓣Oauth类实例
			$config = $this->m_CI->config->item('oauht2');
			$appConfig = $config['douban'];
		
		    $this->m_CI->load->library('Douban/MY_DoubanOauth',$appConfig);
			
			$this->douban = $this->m_CI->my_doubanoauth;
			
		}
		elseif (in_array(T_SINA_TYPE, $this->m_arrLib))
		{
			
		}
	}
	
	private function getToken()
	{
		$acc2platList = $this->m_CI->account_m->getPlatfromList(array('accountID' => $this->m_arrUser['id']));

		foreach ($acc2platList as $v)
		{
			
			if ($v['outTime'] < date('Y-m-d H:i:s',time())) // 过期了..
			{
				// TODO: 需要一个回调页面  用Cookies 传吧
				// TODO: 通过refresh token 获取新的token 判断
				if (in_array($v['platformID'], $this->m_arrLib))
				{
					redirect('oauth2/'.self::$toUrl[$v['platformID']]);
					exit;
				}
				
				
			}
			else
			{
				if ($v['platformID'] == T_SINA_TYPE)
				{
					
				}
				elseif ($v['platformID'] == T_QQ_TYPE)
				{
					
				}
				elseif ($v['platformID'] == QQ_TYPE)
				{
					
				}
				elseif ($v['platformID'] == DOUBAN_TYPE)
				{
					$this->douban->setAccessToken($v['token']);
					$this->douban_uid = $v['openID'];
				}
				elseif ($v['platformID'] == TAOBAO_TYPE)
				{
					
				}
			}
		}
	}
	
}
